package com.yuda.afterexamscore.controller;

import com.yuda.afterexamscore.domain.DpSubjectScore;
import com.yuda.afterexamscore.service.IDpSubjectScoreService;
import com.yuda.afterexamscore.service.IThQuesScoreMappingService;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 单科分数   （如5万个学生应该有5*17=85万条数据)Controller
 *
 * @author wyn
 * @date 2021-05-12
 */
@RestController
@RequestMapping("/dpSubjectScore")
public class DpSubjectScoreController extends BaseController
{
    @Autowired
    private IDpSubjectScoreService dpSubjectScoreService;

    @Autowired
    private IThQuesScoreMappingService thQuesScoreMappingService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询单科分数   （如5万个学生应该有5*17=85万条数据)列表
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:list")
    @GetMapping("/list")
    public TableDataInfo list(DpSubjectScore dpSubjectScore)
    {
        startPage();
        List<DpSubjectScore> list = dpSubjectScoreService.selectDpSubjectScoreList(dpSubjectScore);
        return getDataTable(list);
    }

    /**
     * 导出单科分数   （如5万个学生应该有5*17=85万条数据)列表
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:export")
    @Log(title = "单科分数   （如5万个学生应该有5*17=85万条数据)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DpSubjectScore dpSubjectScore) throws IOException
    {
        List<DpSubjectScore> list = dpSubjectScoreService.selectDpSubjectScoreList(dpSubjectScore);
        ExcelUtil<DpSubjectScore> util = new ExcelUtil<DpSubjectScore>(DpSubjectScore.class);
        util.exportExcel(response, list, "score");
    }

    /**
     * 获取单科分数   （如5万个学生应该有5*17=85万条数据)详细信息
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dpSubjectScoreService.selectDpSubjectScoreById(id));
    }

    /**
     * 新增单科分数   （如5万个学生应该有5*17=85万条数据)
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:add")
    @Log(title = "单科分数   （如5万个学生应该有5*17=85万条数据)", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DpSubjectScore dpSubjectScore)
    {
        return toAjax(dpSubjectScoreService.insertDpSubjectScore(dpSubjectScore));
    }

    /**
     * 修改单科分数   （如5万个学生应该有5*17=85万条数据)
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:edit")
    @Log(title = "单科分数   （如5万个学生应该有5*17=85万条数据)", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DpSubjectScore dpSubjectScore)
    {
        return toAjax(dpSubjectScoreService.updateDpSubjectScore(dpSubjectScore));
    }

    /**
     * 删除单科分数   （如5万个学生应该有5*17=85万条数据)
     */
    @PreAuthorize(hasPermi = "afterexamscore:score:remove")
    @Log(title = "单科分数   （如5万个学生应该有5*17=85万条数据)", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dpSubjectScoreService.deleteDpSubjectScoreByIds(ids));
    }

    @ApiOperation("从dp_ques_score里把数据插入到dp_subject_score,每次执行会把dp_subject_score数据清空,慎用!!!!!!!!!!!!!!!!!!!!!!!!!!,传入字符串数组,学科Id")
    @Log(title = "insertFromDpQuesScore", businessType = BusinessType.INSERT)
    @PostMapping("/insertFromDpQuesScore")
    public AjaxResult insertFromDpQuesScore(@PathVariable String[] subjectIds) throws InterruptedException {
        //计算时间:初始时间
        Instant insOne = Instant.now();
        //先清空dp_ques_score表
        dpSubjectScoreService.truncateTable();
        //分科目插入
        List<String> spartaSubjects= new ArrayList<>(Arrays.asList(subjectIds));
        int threadNum = spartaSubjects.size();
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        ExecutorService executor = Executors.newFixedThreadPool(20);
        if (threadNum>0){
            for (String spartaSubject : spartaSubjects) {
                Runnable task = new DpSubjectScoreController.MultithreadingOfInsertFromDpQuesScore(countDownLatch,spartaSubject);
                // 执行
                executor.execute(task);
            }
        }
        countDownLatch.await();
        executor.shutdown();//关闭线程池
        //计算时间:结束时间
        Instant insTwo = Instant.now();
        return AjaxResult.success("Difference in seconds(秒) : " + Duration.between(insOne, insTwo).getSeconds());
    }

    /**
     * 返回插入进度
     *
     */
    @GetMapping("/insertQuesScoreProcess")
    @ApiOperation("返回插入进度")
    public AjaxResult insertSubjectScoreProcess() throws InterruptedException {
        Boolean flag = redisTemplate.hasKey("dpsubjectcount");
        Object dpsubjectcount = null;
        if (flag){
            //取redis的记录
            dpsubjectcount = redisTemplate.opsForValue().get("dpsubjectcount");
            String count = dpSubjectScoreService.querySubjectScoreCount();
            return AjaxResult.success(Long.parseLong(count)/Long.parseLong(dpsubjectcount.toString()));
        }else {
            return AjaxResult.success(dpSubjectScoreService.insertSubjectScoreProcess());
        }
    }

    //---------------------------------------------------分割线--------------------------------------------------------------------------------------------------

    /**
     * 多线程之插入dp_subject_score
     *
     */
    private class MultithreadingOfInsertFromDpQuesScore implements Runnable {
        private CountDownLatch threadsSignal;
        private String subjectId;
        public MultithreadingOfInsertFromDpQuesScore(CountDownLatch threadsSignal,String subjectId) {
            this.threadsSignal = threadsSignal;
            this.subjectId = subjectId;
        }

        @Override
        public void run() {
            int i = dpSubjectScoreService.insertFromDpQuesScore(subjectId);
            // 线程结束时计数器减1
            threadsSignal.countDown();//必须等核心处理逻辑处理完成后才可以减1
        }
    }
}
